# -*-coding:utf-8-*-
import datetime
import decimal

from lawoffice import settings

from rest_framework.generics import ListAPIView
from rest_framework.permissions import AllowAny, IsAuthenticatedOrReadOnly, IsAuthenticated
from rest_framework.response import Response

from rest_framework.views import APIView
from calculator.models import AreaCode, IndusAverWage, ResIncomeExpend, IncomeExpendItem, Industry
from calculator.api.serializers import AreaCodeSerializer, IndusAverWageSerializer, IncomeExpendItemSerializer, \
    ResIncomeExpendSerializer, IndustrySerializer, ProvinceSerializer
from rest_framework.viewsets import ModelViewSet

NUTRITION_WAGE = 50
MAX_YEARS = 80
MAX_PAY_YEARS = 20
MONTH_WORK_DAYS = 30


class AreaCodeListAPIView(ListAPIView):
    """
    地区编码
    """
    authentication_classes = ()
    permission_classes = [AllowAny]
    queryset = AreaCode.objects.extra(where=['length(code)=2'])
    serializer_class = AreaCodeSerializer
    pagination_class = None


class ProvinceListAPIView(ListAPIView):
    """
    省级编码
    """
    authentication_classes = ()
    permission_classes = [AllowAny]
    queryset = AreaCode.objects.extra(where=['length(code)=2'])
    serializer_class = ProvinceSerializer
    pagination_class = None


class CityListAPIView(ListAPIView):
    """
    市级编码
    """
    authentication_classes = ()
    permission_classes = [AllowAny]
    queryset = AreaCode.objects.extra(where=['length(code)=4'])
    serializer_class = ProvinceSerializer
    pagination_class = None


class IndusAverWageAPIView(APIView):
    """
    行业工资标准
    """
    authentication_classes = ()
    permission_classes = [AllowAny]

    def get(self, request, *args, **kwargs):
        indust_id = request.query_params.get("indust_id", None)
        province = request.query_params.get("province_code", None)
        court_province = request.query_params.get("court_province_code", None)
        print(indust_id, province, court_province)
        indust_wage = IndusAverWage.objects.filter(industry_id=int(indust_id), province_id=province).order_by("-years").first()
        court_indust_wage = IndusAverWage.objects.filter(industry_id=int(indust_id), province_id=court_province).order_by("-years").first()

        result = {
            "success": "false",
        }
        if indust_wage and court_indust_wage:
            if indust_wage.day_aver_wage < court_indust_wage.day_aver_wage:
                indust_wage = court_indust_wage

            serializer = IndusAverWageSerializer(indust_wage)
            result["success"] = "true"
            result["result"] = serializer.data
            return Response(result)
        else:
            result["error_msg"] = "无法获取行业工资标准"
            return Response(result)


class IndusNurseWageAPIView(APIView):
    """
    行业护理日工资标准
    """
    authentication_classes = ()
    permission_classes = [AllowAny]

    def get(self, request, *args, **kwargs):
        province = request.query_params.get("province", None)
        # court_province = request.query_params.get("court_province", None)

        indust_wage = IndusAverWage.objects.filter(province_id=province, industry__standard=1).order_by("-years").first()
        # court_indust_wage = IndusAverWage.objects.filter(province_id=court_province, industry__standard=1).order_by("-years").first()

        result = {
            "success": "false",
        }
        if indust_wage:
            serializer = IndusAverWageSerializer(indust_wage)
            result["success"] = "true"
            result["result"] = serializer.data
            return Response(result)
        else:
            result["error_msg"] = "无法获取护理工资标准"
            return Response(result)


class FuneralExpenseAPIView(APIView):
    """丧葬费"""
    authentication_classes = ()
    permission_classes = [AllowAny]

    def get(self, request, *args, **kwargs):
        dead = request.query_params.get("dead", None)
        province = request.query_params.get("province", None)
        court_province = request.query_params.get("court_province", None)

        result = {
            "success": "false",
        }
        if dead == "1":
            this_year = datetime.datetime.now().year
            last_year = datetime.datetime.now().year - 1
            res_inc_exp = ResIncomeExpend.objects.filter(inc_exp_item_id=5, province_id=province, years=this_year).first()
            court_res_inc_exp = ResIncomeExpend.objects.filter(inc_exp_item_id=5, province_id=court_province, years=this_year).first()

            if res_inc_exp is None:
                res_inc_exp = ResIncomeExpend.objects.filter(inc_exp_item_id=5, province_id=province, years=last_year).first()
                court_res_inc_exp = ResIncomeExpend.objects.filter(inc_exp_item_id=5, province_id=court_province, years=last_year).first()

            # print(res_inc_exp, court_res_inc_exp)

            if res_inc_exp and court_res_inc_exp:
                if res_inc_exp.total_money >= court_res_inc_exp.total_money:
                    result["success"] = "true"
                    result["funeral_expense"] = round(res_inc_exp.total_money / 12 * 6, 2)
                else:
                    result["success"] = "true"
                    result["funeral_expense"] = round(court_res_inc_exp.total_money / 12 * 6, 2)
            else:
                result["funeral_expense"] = 0

        return Response(result)


class IncomeExpendItemViewSet(ModelViewSet):
    """居民人均收支项"""
    authentication_classes = ()
    permission_classes = [AllowAny]
    queryset = IncomeExpendItem.objects.all()
    serializer_class = IncomeExpendItemSerializer
    pagination_class = None


class ResIncomeExpendViewSet(ModelViewSet):
    """居民人均收支情况表"""
    authentication_classes = ()
    permission_classes = [AllowAny]
    queryset = ResIncomeExpend.objects.all()
    serializer_class = ResIncomeExpendSerializer

    def get_queryset(self):
        queryset = super(ResIncomeExpendViewSet, self).get_queryset()
        province = self.request.query_params.get("province", None)
        item = self.request.query_params.get("item", None)
        years = self.request.query_params.get("years", None)
        if province:
            queryset = queryset.filter(province_id=province)

        if item:
            queryset = queryset.filter(inc_exp_item_id=item)

        if years:
            queryset = queryset.filter(years=years)

        return queryset


class IndustryViewSet(ModelViewSet):
    """行业管理"""
    authentication_classes = ()
    permission_classes = [AllowAny]
    pagination_class = None
    queryset = Industry.objects.all()
    serializer_class = IndustrySerializer


class IndusAverWageViewSet(ModelViewSet):
    """分行业城镇单位在岗职工平均工资"""
    authentication_classes = ()
    permission_classes = [AllowAny]
    queryset = IndusAverWage.objects.all()
    serializer_class = IndusAverWageSerializer

    def get_queryset(self):
        queryset = super(IndusAverWageViewSet, self).get_queryset()
        province = self.request.query_params.get("province", None)
        industry = self.request.query_params.get("industry", None)
        years = self.request.query_params.get("years", None)
        if province:
            queryset = queryset.filter(province_id=province)

        if industry:
            queryset = queryset.filter(industry_id=industry)

        if years:
            queryset = queryset.filter(years=years)

        return queryset


class CalculatorAPIView(APIView):
    """交通事故计算"""
    authentication_classes = ()
    permission_classes = [AllowAny]

    def post(self, request, *args, **kwargs):

        spirit_fee = request.data.get("spirit_fee", None)  # 精神抚慰金
        spirit_fee = float(spirit_fee) if spirit_fee else 0.0

        other_fee = request.data.get("other_fee", None)  # 其他费用
        other_fee = float(other_fee) if other_fee else 0.0

        asset_lost = request.data.get("asset_lost", None)  # 财产损失
        asset_lost = float(asset_lost) if asset_lost else 0.0

        hospital_fee = request.data.get("hospital_costs", None)     # 医药费、治疗费
        hospital_fee = float(hospital_fee) if hospital_fee else 0.0

        car_fee = request.data.get("car_fee", None)         # 交通费
        car_fee = float(car_fee) if car_fee else 0.0

        hotel_fee = request.data.get("hotel_fee", None)     # 住宿费
        hotel_fee = float(hotel_fee) if hotel_fee else 0.0

        appraise_fee = request.data.get("appraise_fee", None)   # 鉴定费
        appraise_fee = float(appraise_fee) if appraise_fee else 0.0

        device_cost = request.data.get("device_cost", None)    # 伤残辅助器具费
        device_cost = float(device_cost) if device_cost else 0.0

        dead = request.data.get("dead", None)  # 是否死亡
        if dead == "1":
            funeral_expense = request.data.get("funeral_expense", None)     # 丧葬费
            funeral_expense = float(funeral_expense) if funeral_expense else 0.0
        else:
            funeral_expense = 0.0

        cosmetic_fee = request.data.get("cosmetic_fee", None)    # 整容费
        cosmetic_fee = float(cosmetic_fee) if cosmetic_fee else 0.0
        delay_fee = self.delay_fee(request)  # 误工费
        nurse_fee = self.nurse_fee(request)  # 护理费
        food_allowance = self.food_allowance(request)  # 住院伙食补助费
        nurse_denpendence = self.nurse_denpendence(request)  # 护理依赖费
        nutrition_fee = self.nutrition_fee(request)  # 营养费
        dead_compensation_fee = self.dead_compensation_fee(request)  # 死亡赔偿金
        disability_fee = self.disability_fee(request)    # 伤残赔偿金
        supported_living_expense = self.supported_living_expense(request)    # 生活费
        other_incomes = self.other_income(request)
        print("other-incomes:", other_incomes)
        if other_incomes:
            total_other_incomes = sum([float(item["money"]) for item in other_incomes if item["money"] is not None and item["money"]!=""])
        else:
            total_other_incomes = 0
        print(total_other_incomes)

        totals_money = [
            hospital_fee,
            car_fee,
            hotel_fee,
            appraise_fee,
            spirit_fee,
            other_fee,
            asset_lost,
            device_cost,
            funeral_expense,
            cosmetic_fee,
            delay_fee.get("value", 0),
            nurse_fee.get("value", 0),
            food_allowance.get("value", 0),
            nurse_denpendence.get("value", 0),
            nutrition_fee.get("value", 0),
            dead_compensation_fee.get("value", 0),
            disability_fee.get("value", 0),
            supported_living_expense.get("value", 0)
        ]
        print("totals_money=", totals_money)
        print(sum(totals_money))
        totals_fee = sum(totals_money) + total_other_incomes
        if total_other_incomes == 0:
            other_incomes = []

        results = {
            "hospital_fee": hospital_fee,
            "car_fee": car_fee,
            "hotel_fee": hotel_fee,
            "appraise_fee": appraise_fee,
            "spirit_fee": spirit_fee,
            "other_fee": other_fee,
            "asset_lost": asset_lost,   # 财产损失
            "device_cost": device_cost,
            "funeral_expense": funeral_expense,
            "cosmetic_fee": cosmetic_fee,
            "delay_fee": delay_fee.get("value", 0),
            "nurse_fee": nurse_fee.get("value", 0),
            "food_allowance": food_allowance.get("value", 0),
            "nurse_denpendence": nurse_denpendence.get("value", 0),
            "nutrition_fee": nutrition_fee.get("value", 0),
            "dead_compensation_fee": dead_compensation_fee.get("value", 0),
            "disability_fee": disability_fee.get("value", 0),
            "supported_living_expense": supported_living_expense.get("value", 0),
            "other_incomes": other_incomes,
            "totals_fee": totals_fee,
        }
        return Response({
            "success": True,
            "results": results,
        })

    def get_occur_year(self, request):
        traffic_time = request.data.get("traffic_time", None)
        if traffic_time:
            occur_date = datetime.datetime.strptime(traffic_time, "%Y-%m-%d")
            return occur_date.year
        else:
            return datetime.datetime.now().year

    def other_income(self, request):
        """其他收入"""
        incomes = request.data.get("other_income")
        print(incomes)
        return incomes

    def calc_day_wage(self, request):
        """计算日工资"""
        fix_income = request.data.get("fix_income", None)
        if not fix_income:
            return 0

        if fix_income == "1":       # 有固定收入
            month_income_money = request.data.get("month_income_money", None)
            day_income_money = round(float(month_income_money) / MONTH_WORK_DAYS, 2) if month_income_money else 0.0
            return day_income_money
        else:
            prove_income = request.data.get("prove_income", None)   # 举证日收入
            if prove_income:
                return round(float(prove_income) / MONTH_WORK_DAYS, 2)
            else:
                industry_wage = request.data.get("industry_wage", None)     # 行业收入标准
                industry_wage = industry_wage if industry_wage else "0"
                return float(industry_wage)

    def calc_delay_day(self, request):
        """计算误工时间等于定残时间- 入院时间 + 误工时间"""
        fixed_date = request.data.get("fixed_date", None)   # 定残日期
        enter_time = request.data.get("enter_time", None)  # 入院时间
        leave_time = request.data.get("leave_time", None)  # 出院时间
        if fixed_date:
            if enter_time:
                delay_duration = request.data.get("delay_duration", None)   # 误工期限
                delay_duration = delay_duration if delay_duration else "0"
                d_fixed_date = datetime.datetime.strptime(fixed_date, "%Y-%m-%d").date()
                d_enter_date = datetime.datetime.strptime(enter_time, "%Y-%m-%d").date()
                day_diff = (d_fixed_date - d_enter_date).days
                return day_diff + int(delay_duration)
        else:
            # 计算误工时间等于出院时间 - 入院时间 + 1 + 误工时间 + 休养时间
            if enter_time and leave_time:
                rest_day = request.data.get("rest_day", None)   # 医嘱中需要休养天数
                rest_day = rest_day if rest_day else "0"
                delay_duration = request.data.get("delay_duration", None)   # 误工期限
                delay_duration = delay_duration if delay_duration else "0"

                d_enter_time = datetime.datetime.strptime(enter_time, "%Y-%m-%d").date()
                d_leave_time = datetime.datetime.strptime(leave_time, "%Y-%m-%d").date()
                day_diff = (d_leave_time - d_enter_time).days + 1
                return day_diff + int(rest_day) + int(delay_duration)

        return 0

    def delay_fee(self, request, *args, **kwargs):
        """误工费"""
        day_wage = self.calc_day_wage(request)
        delay_days = self.calc_delay_day(request)
        value = day_wage * delay_days
        formats = "{} X {} = {}".format(day_wage, delay_days, value)
        print(formats)
        delay_fee = {
            "value": value,
            "formats": formats,
        }
        return delay_fee

    def nurse_fee(self, request):
        """护理费用"""
        nurse_one_wage = request.data.get("nurse_one_wage", None)
        nurse_one_wage = float(nurse_one_wage) if nurse_one_wage else 0.0

        nurse_one_days = request.data.get("nurse_one_days", None)
        nurse_one_days = float(nurse_one_days) if nurse_one_days else 0.0

        nurse_two_wage = request.data.get("nurse_two_wage")
        nurse_two_wage = float(nurse_two_wage) if nurse_two_wage else 0.0

        nurse_two_days = request.data.get("nurse_two_days", None)
        nurse_two_days = float(nurse_two_days) if nurse_two_days else 0.0

        nurse_three_wage = request.data.get("nurse_three_wage")
        nurse_three_wage = float(nurse_three_wage) if nurse_three_wage else 0.0

        nurse_three_days = request.data.get("nurse_three_days", None)
        nurse_three_days = float(nurse_three_days) if nurse_three_days else 0.0

        value =nurse_one_wage * nurse_one_days + nurse_two_wage * nurse_two_days + nurse_three_wage * nurse_three_days

        if nurse_two_wage > 0 and nurse_two_days > 0:
            formats = "{} X {} + {} X {} = {}".format(nurse_one_wage, nurse_one_days, nurse_two_wage, nurse_two_days, value)
        elif nurse_three_wage > 0 and nurse_three_days > 0:
            formats = "{} X {} + {} X {} + {} X {} = {}".format(nurse_one_wage, nurse_one_days, nurse_two_wage, nurse_two_days, nurse_three_wage, nurse_three_days, value)
        else:
            formats = "{} X {} = {}".format(nurse_one_wage, nurse_one_days, value)

        nurse_fee = {
            "value": value,
            "formats": formats
        }
        return nurse_fee

    def food_allowance(self, request):
        """伙食补助"""
        # 读取伙食补助标准 id = 7
        # province = request.data.get("province_code", None)
        year = self.get_occur_year(request)
        court_province = request.data.get("court_province_code", None)
        res_income_expend = ResIncomeExpend.objects.filter(inc_exp_item_id=7, province_id=court_province, years=year).first()
        if res_income_expend is None:
            res_income_expend = ResIncomeExpend.objects.filter(inc_exp_item_id=7, province_id=court_province,
                                                               years=year - 1).first()
        if res_income_expend:
            hospital_day = request.data.get("hospital_day", None)
            hospital_day = float(hospital_day) if hospital_day else 0.0
            value = float(res_income_expend.total_money) * hospital_day
            formats = "{} X {} = {}".format(res_income_expend.total_money, hospital_day, value)
        else:
            value = 0
            formats = "无伙食补助标准"

        food_allowance = {
            "value": value,
            "formats": formats,
        }
        return food_allowance

    def nurse_denpendence(self, request):
        """护理依赖费"""
        # 读取护理依赖费标准 id = 5(城镇单位在岗职工平均工资)
        province = request.data.get("province_code", None)
        court_province = request.data.get("court_province_code", None)
        res_income_expend = ResIncomeExpend.objects.filter(inc_exp_item_id=5, province_id=province).order_by("-years").first()
        court_res_income_expend = ResIncomeExpend.objects.filter(inc_exp_item_id=5,
                                                                 province_id=court_province).order_by("-years").first()

        if res_income_expend and court_res_income_expend:
            total_money = res_income_expend.total_money if res_income_expend.total_money >= court_res_income_expend.total_money else court_res_income_expend.total_money
            nurse_depend_duration = request.data.get("nurse_depend_duration", None)
            nurse_depend_duration = int(nurse_depend_duration) if nurse_depend_duration else 0

            nurse_depend_level = request.data.get("nurse_depend_level", None)
            nurse_depend_level = int(nurse_depend_level) if nurse_depend_level else 0
            value = total_money / 365 * nurse_depend_level / 100 * nurse_depend_duration
            value = float(value.quantize(decimal.Decimal("0.01")))
            formats = "({} / 365) X ({}/100) X {} = {}".format(total_money, nurse_depend_level, nurse_depend_duration,
                                                               value)
        else:
            value = 0
            formats = "无护理依赖标准"

        nurse_denpendence = {
            "value": value,
            "formats": formats,
        }
        return nurse_denpendence

    def nutrition_fee(self, request):
        """营养费"""
        nutrition = request.data.get("nutrition", None)

        year = self.get_occur_year(request)
        court_province = request.data.get("court_province_code", None)
        res_income_expend = ResIncomeExpend.objects.filter(inc_exp_item_id=8, province_id=court_province,
                                                           years=year).first()
        if res_income_expend is None:
            res_income_expend = ResIncomeExpend.objects.filter(inc_exp_item_id=8, province_id=court_province,
                                                               years=year - 1).first()

        if res_income_expend:
            _wage = float(res_income_expend.total_money)
        else:
            _wage = float(NUTRITION_WAGE)

        if nutrition == "1":
            hospital_day = request.data.get("hospital_day", None)
            hospital_day = int(hospital_day) if hospital_day else 0
        else:
            hospital_day = 0

        nutrition_duration = request.data.get("nutrition_duration", None)
        nutrition_duration = int(nutrition_duration) if nutrition_duration else 0

        leave_nutrition_fee = request.data.get("leave_nutrition_fee", None)
        leave_nutrition_fee = int(leave_nutrition_fee) if leave_nutrition_fee else 0

        value = (hospital_day + nutrition_duration) * _wage + leave_nutrition_fee
        formats = "({} + {}) X {} + {} = {}".format(hospital_day, nutrition_duration, NUTRITION_WAGE, leave_nutrition_fee, value)

        nutrition_fee = {
            "value": value,
            "formats": formats,
        }
        return nutrition_fee

    def compensation_years(self, age):
        """赔偿年限"""
        if age <= 60:
            return 20
        elif 60 < age <= 75:
            return 20 - (age - 60)
        else:
            return 5

    def compensation_wage(self, province, court_province):
        """赔偿标准"""
        year = self.get_occur_year(self.request)

        res_income_expend = ResIncomeExpend.objects.filter(inc_exp_item_id=1, province_id=province, years=year).first()
        court_res_income_expend = ResIncomeExpend.objects.filter(inc_exp_item_id=1, province_id=court_province, years=year).first()

        if res_income_expend is None and court_res_income_expend is None:
            res_income_expend = ResIncomeExpend.objects.filter(inc_exp_item_id=1, province_id=province,
                                                               years=year - 1).first()
            court_res_income_expend = ResIncomeExpend.objects.filter(inc_exp_item_id=1, province_id=court_province,
                                                                     years=year - 1 ).first()

        if res_income_expend and court_res_income_expend:
            total_money = res_income_expend.total_money if res_income_expend.total_money >= court_res_income_expend.total_money else court_res_income_expend.total_money
            return float(total_money)
        else:
            return -1

    def dead_compensation_fee(self, request):
        """死亡赔偿金"""
        dead = request.data.get("dead")
        if dead and dead == "1":
            age = request.data.get("age", "0")
            province = request.data.get("province_code", None)
            court_province = request.data.get("court_province_code", None)
            compen_years = self.compensation_years(int(age))
            compen_wage = self.compensation_wage(province, court_province)

            if compen_wage != -1:
                value = compen_wage * compen_years
                formats = "{} X {} = {}".format(compen_wage, compen_years, value)
            else:
                value = 0
                formats = "无法正确读取居民人均可支配收入"

            dead_compensation_fee = {
                "value": value,
                "formats": formats,
            }
        else:
            dead_compensation_fee = {
                "value": 0,
                "formats": "",
            }
        return dead_compensation_fee

    def disability_fee(self, request):
        """伤残赔偿金"""
        dead = request.data.get("dead", "0")
        disability_fee = {
            "value": 0,
            "formats": "",
        }
        if not dead or dead == "0":
            age = request.data.get("age", "0")
            province = request.data.get("province_code")
            court_province = request.data.get("court_province_code")
            compen_years = self.compensation_years(int(age))
            compen_wage = self.compensation_wage(province, court_province)
            if compen_wage == -1:
                disability_fee["value"] = 0
                disability_fee["formats"] = "无法正确读取居民人均可支配收入"
            else:
                top_disability = request.data.get("top_disability_id", None)
                top_disability = int(top_disability) if top_disability else 0
                sec_disability = request.data.get("sec_disability", None)

                sec_disability_sum = 0
                if sec_disability:
                    sec_disability_sum = sum([int(item["id"]) for item in sec_disability if item["id"] != ''])

                disability_factors = top_disability + sec_disability_sum
                value = compen_wage * compen_years * disability_factors/100
                formats = "{} X {} X {}/100".format(compen_wage, compen_years, disability_factors)
                disability_fee["value"] = value
                disability_fee["formats"] = formats

        return disability_fee

    def per_consumption_expend(self, province, court_province):
        """居民人均消费支出"""
        year = self.get_occur_year(self.request)
        res_income_expend = ResIncomeExpend.objects.filter(inc_exp_item_id=3, province_id=province, years=year).first()
        court_res_income_expend = ResIncomeExpend.objects.filter(inc_exp_item_id=3, province_id=court_province, years=year).first()
        if res_income_expend is None and court_res_income_expend is None:
            res_income_expend = ResIncomeExpend.objects.filter(inc_exp_item_id=3, province_id=province,
                                                               years=year - 1).first()
            court_res_income_expend = ResIncomeExpend.objects.filter(inc_exp_item_id=3, province_id=court_province,
                                                                     years=year - 1).first()

        if res_income_expend and court_res_income_expend:
            return res_income_expend.total_money if res_income_expend.total_money >= court_res_income_expend.total_money else court_res_income_expend.total_money
        else:
            return -1

    def supported_living_expense(self, request):
        """被抚(扶)养人生活费"""
        relations = request.data.get("relations")
        supports = request.data.get("supports")
        province = request.data.get("province_code")
        court_province = request.data.get("court_province_code")

        per_consumption_exp = self.per_consumption_expend(province, court_province)

        living_expense = {
            "value": 0,
            "formats": "无法正确读取居民人均消费支出"
        }
        if per_consumption_exp == -1:
            return living_expense

        # 配偶情况
        PARTNER = 5  # 配偶
        BROTHOR = 6  # 兄弟姐妹
        join_partner = 1
        broth_sist_counts = 1
        for relation in relations:
            if not relation or relation["relation_type"] is None:
                continue
            # 配偶
            if relation["relation_type"] == PARTNER:
                if relation["is_income"] == "0" or relation["action_ability"] == "1" or int(relation["relation_age"]) >= 60:
                    pass
                else:
                    join_partner += 1
            # 兄弟姐妹
            if relation["relation_type"] == BROTHOR:
                if relation["is_income"] == 1 and relation["action_ability"] == 0 and 60 > int(relation["relation_age"]) >= 18:
                    broth_sist_counts += 1

        # 计算赔偿年限
        expense_day = []
        for s in supports:
            if not s or s["relation_age"] is None:
                continue
            age = int(s["relation_age"])
            if s["relation_type"] == 3:  # 子女
                if s["action_ability"] == "1":  # 残障
                    expense_day.append((MAX_PAY_YEARS, s["relation_type"]))
                else:  # 无残障
                    if age < 18:
                        expense_day.append((18 - age, s["relation_type"]))
            elif s["relation_type"] == 5:  # 配偶
                if s["action_ability"] == "1":
                    if age < 60:
                        expense_day.append((MAX_PAY_YEARS, s["relation_type"]))
                    else:
                        expense_day.append((MAX_YEARS - age, s["relation_type"]))
            elif s["relation_type"] == 1 or s["relation_type"] == 2:  # 父母
                if age < 60 and (s["action_ability"] == "1" or s["is_income"] == "0"):  # 未到60有残障或无生活来源
                    expense_day.append((MAX_PAY_YEARS, s["relation_type"]))

                elif age >= 60:
                    expense_day.append((MAX_YEARS - age, s["relation_type"]))

        expense_day.sort()
        print(expense_day)
        list_expense = []
        for i in range(0, len(expense_day)):
            if i == 0:
                list_expense.append((expense_day[i][0], expense_day[i][1]))
                # list_expense.append((expense_day[i][0] - expense_day[i - 1][0], expense_day[i][1]))
            else:
                list_expense.append((expense_day[i][0] - expense_day[i - 1][0], expense_day[i][1]))

        print("list_expense:", list_expense)

        list_expense_ex = []
        for i in range(0, len(list_expense)):
            dict_expense = {
                "years": list_expense[i][0],
                "persons": []
            }
            for j in range(i, len(list_expense)):
                dict_expense["persons"].append(list_expense[j][1])

            list_expense_ex.append(dict_expense)

        print("list_expense_ex:", list_expense_ex)

        list_expense_result = [item for item in list_expense_ex if item["years"] > 0]

        list_total_expense = []
        for item in list_expense_result:
            years = item["years"]
            phase_expense = []
            persons = item["persons"]
            max_expense = per_consumption_exp * years
            for ptype in persons:
                if ptype == 3:  # 子女
                    expense = per_consumption_exp * years / join_partner
                    phase_expense.append(expense)
                elif ptype == 1 or ptype == 2:  # 父母
                    expense = per_consumption_exp * years / broth_sist_counts
                    phase_expense.append(expense)

            phase_expense_sum = sum(phase_expense)
            phase_expense_sum = phase_expense_sum if phase_expense_sum <= max_expense else max_expense
            list_total_expense.append(phase_expense_sum)

        total_expense_sum = sum(list_total_expense)
        formats = [str(item) for item in list_total_expense]
        living_expense["value"] = float(total_expense_sum)
        living_expense["formats"] = "{} = {}".format(" + ".join(formats), total_expense_sum)
        print(living_expense)

        return living_expense
